package com.gryffonx.NameGenerators;

import com.gryffonx.DiceRoller.StaticDiceRoller;
import com.gryffonx.utils.StringUtils;
import com.gryffonx.utils.XMLUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.io.File;


/**
 * @author Erik Stell
 * @version 1.0
 */
public class NationNameGenerator {
    private static final File fileToBeParsed = new File("src/com/gryffonx/xml/nations.xml");
    private static final SAXReader reader = new SAXReader();
    private static Document xmlDoc = null;

    public static String generateName(int howMany) {
        if (howMany <= 0) {
            howMany = 1;
        }

        try {
            xmlDoc = reader.read(fileToBeParsed);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuffer retVal = new StringBuffer();

        for (int i = 0; i < howMany; i++) {
            StringBuffer finishedName = new StringBuffer();

            try {
                finishedName.append(getPrefix(
                        determineGroup()));
                finishedName.append(getMiddle());
                finishedName.append(getSuffix());
            } catch (Exception e) {
                e.printStackTrace();
            }

            retVal.append(StringUtils.capitalize(finishedName.toString()));
            // retVal.append("\n");
        }

        return retVal.toString();
    }

    private static String getPrefix(String group) {
        String retVal = "";
        try {
            retVal = StringUtils.capitalize(XMLUtils.getNodeValue("prefix", xmlDoc, Integer.parseInt(group)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return retVal;
    }

    private static String getMiddle() {
        String retVal = "";

        try {
            retVal = XMLUtils.getNodeValue("middle", xmlDoc, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return retVal;
    }

    private static String getSuffix() {
        String retVal = "";
        try {
            retVal = XMLUtils.getNodeValue(xmlDoc, "nation");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retVal;
    }

    private static String determineGroup() {
        return String.valueOf(StaticDiceRoller.rolldSomething(2, 1));
    }
}
